<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="data.title" prefix-icon="Search" style="width: 240px;" placeholder="请输入指南标题查询"></el-input>
      <el-autocomplete
          v-model="data.plantInput"
          :fetch-suggestions="querySearch"
          placeholder="请选择或输入植物名称"
          clearable
          style="width: 200px; margin-right: 10px"
          @select="handleSelect"
      >
        <template #suffix>
          <i class="el-input__icon el-icon-search"></i>
        </template>
        <template #default="{ item }">
          <div>{{ item.chineseName }}</div>
        </template>
      </el-autocomplete>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain @click="reset">重置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-table stripe :data="data.tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="img" label="指南图片" width="100">
          <template v-slot="scope">
            <el-image style="width: 60px; height: 40px; border-radius: 5px; display: block" v-if="scope.row.img"
                      :src="scope.row.img" :preview-src-list="[scope.row.img]" preview-teleported></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" show-overflow-tooltip/>
        <el-table-column prop="plantChineseName" label="中文名" show-overflow-tooltip/>
        <el-table-column prop="plantLatinName" label="拉丁名" show-overflow-tooltip/>
        <el-table-column label="标签" show-overflow-tooltip>
          <template v-slot="scope">
            <el-tag v-for="(tag, index) in scope.row.tags ? JSON.parse(scope.row.tags) : []" :key="index" style="margin-right: 5px;">
              {{ tag }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdByUsername" label="创建者" show-overflow-tooltip/>
        <el-table-column prop="createdAt" label="创建时间" width="180"/>
        <el-table-column label="操作" width="100" fixed="right">
          <template v-slot="scope">
            <el-button type="primary" circle :icon="Edit" @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" circle :icon="Delete" @click="del(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card" v-if="data.total">
      <el-pagination @current-change="load" background layout="prev, pager, next" :page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total" />
    </div>
    <el-dialog title="编辑植物指南" v-model="data.formVisible" width="60%" destroy-on-close>
      <el-form ref="form" :model="data.form" label-width="100px" style="padding: 20px">
        <el-form-item prop="title" label="标题">
          <el-input v-model="data.form.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item prop="plantId" label="植物名称">
          <el-autocomplete
              v-model="data.form.plantInput"
              :fetch-suggestions="querySearch"
              placeholder="请选择或输入植物名称"
              clearable
              @select="handleFormSelect"
          >
            <template #suffix>
              <i class="el-input__icon el-icon-search"></i>
            </template>
            <template #default="{ item }">
              <div>{{ item.chineseName }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="指南图片">
          <el-upload
              :action="uploadUrl"
              :on-success="handleFileUpload"
              :before-upload="beforeUpload"
              :show-file-list="false"
              class="avatar-uploader"
          >
            <img v-if="data.form.img" :src="data.form.img" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item prop="guideContent" label="指南内容">
          <div style="border: 1px solid #ccc; width: 100%">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="data.form.guideContent"
                :mode="mode"
                :default-config="editorConfig"
                @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
        <el-form-item prop="tags" label="标签">
          <el-input v-model="data.form.tags" placeholder="请输入标签，逗号分隔"></el-input>
        </el-form-item>
        <el-form-item label="创建者">
          <el-input v-model="data.form.createdByUsername" disabled></el-input>
        </el-form-item>
        <el-form-item label="更新者">
          <el-input v-model="data.form.updatedByUsername" disabled></el-input>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="data.form.createdAt" disabled></el-input>
        </el-form-item>
        <el-form-item label="更新时间">
          <el-input v-model="data.form.updatedAt" disabled></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 显示 guideContent 的对话框 -->
    <el-dialog title="指南详情" v-model="data.detailsVisible" width="60%" destroy-on-close>
      <div v-html="data.selectedRow.guideContent"></div>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, onMounted, ref } from "vue";
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit, Plus } from "@element-plus/icons-vue";
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

const data = reactive({
  user: JSON.parse(localStorage.getItem('user') || '{}'),
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  title: null,
  plantInput: null,
  plantId: null,
  plants: [],
  form: {
    id: null,
    title: '',
    img: '',
    plantInput: null,
    plantId: null,
    guideContent: '',
    tags: '',
    createdByUsername: null,
    updatedByUsername: null,
    createdAt: null,
    updatedAt: null
  },
  formVisible: false,
  detailsVisible: false,
  selectedRow: {},
  ids: []
});

const editorConfig = {
  MENU_CONF: {
    uploadImage: {
      headers: {
        token: data.user.token,
      },
      server: 'http://localhost:8080/files/wang/upload',
      fieldName: 'file'
    }
  }
};

const editorRef = ref(null);
const mode = 'simple';

const handleCreated = (editor) => {
  editorRef.value = editor;
};

const loadPlants = async () => {
  try {
    const response = await request.get('/plantInfo/baseMesgPlant');
    if (response.code === '200') {
      data.plants = response.data;
    }
  } catch (error) {
    console.error('加载植物信息失败:', error);
    ElMessage.error('加载植物信息失败');
  }
};

const querySearch = (queryString, cb) => {
  const results = queryString ? data.plants.filter(plant => plant.chineseName.includes(queryString)) : data.plants;
  // 调用 callback 返回建议列表的数据
  cb(results.map(plant => ({ value: plant.id, chineseName: plant.chineseName })));
};

const handleSelect = (item) => {
  data.plantInput = item.chineseName;
  data.plantId = item.value;
};

const handleFormSelect = (item) => {
  data.form.plantInput = item.chineseName;
  data.form.plantId = item.value;
};

const load = async () => {
  try {
    const response = await request.get('/plantGuide/selectPage', {
      params: {
        plantId: data.plantId,
        title: data.title,
        pageNum: data.pageNum,
        pageSize: data.pageSize
      }
    });
    if (response.code === '200') {
      data.tableData = response.data.list;
      data.total = response.data.total;
    }
  } catch (error) {
    console.error('加载种植指南失败:', error);
    ElMessage.error('加载种植指南失败');
  }
};

const reset = () => {
  data.title = null;
  data.plantInput = null;
  data.plantId = null;
  data.pageNum = 1;
  load();
};

const handleSelectionChange = (val) => {
  data.ids = val.map(item => item.id);
};

const delBatch = async () => {
  if (!data.ids.length) {
    ElMessage.warning("请选择数据");
    return;
  }
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', {type: 'warning'}).then(() => {
    request.delete("/plantGuide/delete/batch", {data: data.ids}).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功');
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(err => {
    console.error(err);
  });
};

const handleAdd = () => {
  data.form = {
    id: null,
    title: '',
    img: '',
    plantInput: null,
    plantId: null,
    guideContent: '',
    tags: '',
    createdByUsername: null,
    updatedByUsername: null,
    createdAt: null,
    updatedAt: null
  };
  data.formVisible = true;
};

const handleEdit = (row) => {
  request.get(`/plantGuide/selectById/${row.id}`).then(res => {
    if (res.code === '200') {
      const plant = data.plants.find(p => p.id === res.data.plantId);
      data.form = {
        ...res.data,
        plantInput: plant ? plant.chineseName : ''
      };
      data.formVisible = true;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const save = () => {
  if (data.form.id) {
    request.put('/plantGuide/update', data.form).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功');
        data.formVisible = false;
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  } else {
    request.post('/plantGuide/add', data.form).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功');
        data.formVisible = false;
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }
};

const del = (id) => {
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', {type: 'warning'}).then(() => {
    request.delete(`/plantGuide/delete/${id}`).then(res => {
      if (res.code === '200') {
        ElMessage.success("删除成功");
        load();
      } else {
        ElMessage.error(res.msg);
      }
    }).catch(err => {
      console.error(err);
    });
  });
};

const baseUrl = import.meta.env.VITE_BASE_URL;
const uploadUrl = `${baseUrl}/files/upload`;

const handleFileUpload = (response) => {
  data.form.img = response.data; // 保存返回的图片URL
  ElMessage.success('上传成功');
};

const beforeUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
  }
  return isImage;
};

onMounted(() => {
  loadPlants();
  load();
});
</script>




<style scoped>
.card {
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fff;
}

.el-tag {
  margin-right: 5px;
}

.avatar {
  width: 120px;
  height: 120px;
  object-fit: cover;
  cursor: pointer; /* 鼠标悬停时显示可点击的样式 */
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
</style>
